package com.yidiandao.business.data.model;

import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.event.RefreshSecondKillEvent;
import com.yidiandao.business.data.imagemodule.SecondKill;
import com.yidiandao.business.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;

/** 秒杀活动对象计时器 */
class SecondKillTimer implements Runnable {

    private final SecondKill.TimeInfo timeInfo;
    private SecondKill secondKill;
    private long serverNowTime;

    SecondKillTimer(SecondKill secondKill) {
        this.secondKill = secondKill;

        serverNowTime = secondKill.getServerNowTime();

        timeInfo = secondKill.getTimeInfo();

        // 初始化当前场次秒杀活动的状态
        refreshLeaveTime();
    }

    private void refreshLeaveTime() {

        long startTime = timeInfo.getStartTime();
        long endTime = timeInfo.getEndTime();

        if (serverNowTime <= startTime) {
            // 当前场秒杀活动未开始
            secondKill.setState(Goods.ACTIVE_STATE.UN_START);
            secondKill.setLeaveTime(startTime - serverNowTime);
        } else if (serverNowTime > startTime && serverNowTime <= endTime) {
            // 当前场秒杀活动正在进行中
            secondKill.setState(Goods.ACTIVE_STATE.RUNNING);
            secondKill.setLeaveTime(endTime - serverNowTime);
        } else {
            // 当前场秒杀活动已结束
            secondKill.setState(Goods.ACTIVE_STATE.FINISHED);
        }
    }

    @Override
    public void run() {

        // 倒计时走到0时，停止倒计时
        if (secondKill.getLeaveTime() == 0) {
            stopTimer();
            postRefreshSecondKillEvent();
            return;
        }

        serverNowTime++;

        // todo 记录新的ServerNowTime
        //        secondKill.setServerNowTime(serverNowTime);

        refreshLeaveTime();

        UIUtils.postDelayed(this, 1000);
    }

    void startTimer() {
        stopTimer();
        UIUtils.postDelayed(this, 1000);
    }

    void stopTimer() {
        UIUtils.removeCallbacks(this);
    }

    private void postRefreshSecondKillEvent() {
        EventBus.getDefault().post(new RefreshSecondKillEvent());
    }
}
